<?php

namespace service;

class Rsa
{
    private $_config = [
        'public_key'  => '',
        'private_key' => '',
    ];

    public function __construct($private_key_filepath, $public_key_filepath)
    {
        $this->_config['private_key'] = $this->_getContents($private_key_filepath);
        $this->_config['public_key']  = $this->_getContents($public_key_filepath);
    }

    //获取文件内容
    private function _getContents($file_path)
    {
        file_exists($file_path) or die ('密钥或公钥的文件路径错误');
        return file_get_contents($file_path);
    }

    //获取私钥
    private function _getPrivateKey()
    {
        $priv_key = $this->_config['private_key'];
        //转换为openssl密钥，必须是没有经过pkcs8转换的私钥
        return openssl_get_privatekey($priv_key);
    }

    //获取公钥
    private function _getPublicKey()
    {
        $public_key = $this->_config['public_key'];
        return openssl_pkey_get_public($public_key);
    }

    //私钥加密
    public function privEncrypt($data = '')
    {
        if (!is_string($data)) {
            return null;
        }
        $PrivateKey=$this->_getPrivateKey();
        $encrypt='';
        foreach (str_split($data,117) as $item){
            openssl_private_encrypt($item,$temp,$PrivateKey);
            $encrypt.=$temp;
        }
        openssl_free_key($PrivateKey);
        return base64_encode($encrypt);
    }

    //公钥加密
    public function publicEncrypt($data = '')
    {
        if (!is_string($data)) {
            return null;
        }
        $publicKey=$this->_getPublicKey();
        $encrypt='';
        foreach (str_split($data,117) as $item){
            openssl_public_encrypt($item,$temp,$publicKey);
            $encrypt.=$temp;
        }
        openssl_free_key($publicKey);
        return base64_encode($encrypt);
    }

    //私钥解密
    public function privDecrypt($encrypted = '')
    {
        if (!is_string($encrypted)) {
            return null;
        }
        return (openssl_private_decrypt($encrypted, $decrypted, $this->_getPrivateKey())) ? $decrypted : null;
    }

    //公钥解密
    public function publicDecrypt($encrypted = '')
    {
        if (!is_string($encrypted)) {
            return null;
        }
        return (openssl_public_decrypt(base64_decode($encrypted), $decrypted, $this->_getPublicKey())) ? $decrypted : null;
    }

    //签名
    public function sign($data = '',$signature_alg=OPENSSL_ALGO_SHA1)
    {
        if (!is_string($data)) {
            return null;
        }
        $priv_key = $this->_config['private_key'];
        //转换为openssl密钥，必须是没有经过pkcs8转换的私钥
        $PrivateKey= openssl_get_privatekey($priv_key);
        //调用openssl内置签名方法，生成签名$sign
        openssl_sign($data, $sign, $PrivateKey,$signature_alg);
        //释放资源
        openssl_free_key($PrivateKey);
        return $sign;
    }
}